package main

import (
	"fmt"
	_ "net/http/pprof"
	"os"
	"os/signal"
	"path"
	"src/gcommon"
	"src/server/Login/handler"
	"src/server/Login/server"
	"src/zeus/common"
	"src/zeus/iserver"
	"src/zeus/logger"
	"src/zeus/threads"
	"strings"
	"syscall"

	"github.com/buguang01/util/flags"

	"github.com/spf13/viper"
)

func main() {
	//flags.SetFlag(common.PrivateService, strings.ToUpper(common.PrivateService), "私服标记", "false")
	//flags.SetFlag(common.ServerJson, strings.ToUpper(common.ServerJson), "服务器配置文件路径，相对与bin目录", path.Join(common.GetResPath(), "config", "server.json"))
	flags.SetFlag(common.ServerName, strings.ToUpper(common.ServerName), "服务器名字，表示server.json中的名字", "Login")
	flags.SetFlag(common.ServerCreateDB, strings.ToUpper(common.ServerCreateDB), "是否创建和更新数据库：[0:读server.json;1:创建;2:不创建]", "0")
	flags.Parse()
	viper.SetConfigFile(flags.GetFlagByString(common.ServerJson))
	if err := viper.ReadInConfig(); err != nil {
		panic("加载配置文件失败")
	}
	servername := flags.GetFlagByString(common.ServerName)
	logger.Init(path.Join(common.GetResPath(), "config", "log.toml"), servername, threads.NewThreadGo())
	gcommon.SetServerConfig(viper.GetViper())
	defer logger.Flush()
	vipconfig := viper.New()
	vipconfig.MergeConfigMap(viper.GetStringMap(servername))
	serinfo := iserver.GetServerBase(vipconfig)

	threads.SetUtilLog(func(err interface{}) {
		buf := common.StackTrace()
		common.UpPanic(common.NewPanicSrvMD(
			int(serinfo.GroupID),
			gcommon.ServerTypeLogin,
			int(serinfo.SrvID),
			"",
			err,
			buf,
		))
		if !viper.GetBool("Config.Recover") {
			panic(fmt.Sprintf("Log: %s", buf))
		} else {
			logger.Error("Log:", err)
		}
	})
	srv := server.GetServer()
	LoginSrvVerifyToken := viper.GetString("Config.LoginSrvVerifyToken")
	srv.LoginSrvVerifyToken = LoginSrvVerifyToken

	srv.SetRouter(handler.GetRouter())
	// excel.Init()

	srv.Run()
	logger.Info("Login Start.")

	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGINT, syscall.SIGKILL, syscall.SIGTERM)
	<-c
	srv.Stop()

}
